package com.businessportal.web.dataaccess.utils;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Created by Vadim on 6/20/14.
 */
public class HibernateUtil {
    private static String dbUrl;
    private static SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            dbUrl = getDbUrlConnectionString();
            System.out.println("DbUrl: " + dbUrl);
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration configuration = new Configuration().configure();


            //uncomment for remote location
            //if(SettingsConfig.getInstance().IsRemoteDeployment()){
            //    configuration.setProperty("hibernate.connection.url", dbUrl);
            //}

            ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
            registry.applySettings(configuration.getProperties());
            ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
            return configuration.buildSessionFactory(serviceRegistry);
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    private static String getDbUrlConnectionString(){
        String dbHost = System.getenv("OPENSHIFT_MYSQL_DB_HOST");
        String dbPort = System.getenv("OPENSHIFT_MYSQL_DB_PORT");
        String appName = System.getenv("OPENSHIFT_APP_NAME");
        return "jdbc:mysql://" + dbHost + ":" + dbPort + "/" + appName + "?characterEncoding=UTF-8";
    }

    private static boolean IsDbUrlChnaged(){
        String newDbUrl = getDbUrlConnectionString();
        System.out.println("dbUrl:" + dbUrl + " newDbUrl:" + newDbUrl);
        return !dbUrl.equalsIgnoreCase(newDbUrl);
    }

    public static SessionFactory getSessionFactory() {

        /*if(IsDbUrlChnaged()){

            shutdown();
            sessionFactory = buildSessionFactory();
        }*/

        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and connection pools
        getSessionFactory().close();
    }
}
